import { createRouter, createWebHistory } from 'vue-router';
import LoginPage from '@/components/LoginPage.vue';
import RegisterPage from '@/components/RegisterPage.vue';
import WelcomePage from '@/components/WelcomePage.vue';
import FundDashboard from '@/components/FundDashboard.vue';
import IndexAnalysisPage from '@/components/IndexAnalysisPage.vue';
import FavoritesPage from '@/components/FavoritesPage.vue';

const routes = [
  { path: '/login', component: LoginPage },
  { path: '/register', component: RegisterPage },
  {
    path: '/welcome',
    component: WelcomePage,
    meta: { requiresAuth: true }
  },
  {
    path: '/dashboard/fund/:type/:board',
    name: 'FundDashboardByType',
    component: FundDashboard,
    props: true,
    meta: { requiresAuth: true }
  },
  {
    path: '/dashboard/index/:board',
    name: 'IndexDashboardByType',
    component: () => import('@/components/IndexDashboard.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/dashboard/index/analysis',
    name: 'IndexAnalysis',
    component: IndexAnalysisPage,
    meta: { requiresAuth: true }
  },
  {
    path: '/dashboard/favorites',
    name: 'Favorites',
    component: FavoritesPage,
    meta: { requiresAuth: true }
  },
  { path: '/', redirect: '/login' }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'; // 检查登录状态

  if (to.meta.requiresAuth && !isLoggedIn) {
    // 如果路由需要认证且用户未登录，则重定向到登录页
    next('/login');
  } else {
    // 否则允许访问
    next();
  }
});

export default router;
